package com.example.mqtt.service.impl;

import com.example.mqtt.entity.User;
import com.example.mqtt.mapper.UserMapper;
import com.example.mqtt.service.UserService;
import com.example.mqtt.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/5/18 19:08
 **/
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    @Override
    public String checkUserLogin(String username, String password) {
        User user = userMapper.getUserByUserName(username, password);
        if (user == null) {
            throw new RuntimeException("当前登录用户不存在，请检查账号密码后重试。");
        }

        return JwtUtil.generateToken(user.getUserId(), user.getUsername());
    }

    @Override
    public String registerUser(User saveUser) {
        User user = userMapper.queryUserByUsername(saveUser.getUsername());
        if (user != null) {
            throw new RuntimeException("当前注册用户已存在，请更换用户名。");
        }

        saveUser.setUserId(UUID.randomUUID().toString());
        userMapper.registerUser(saveUser);
        return JwtUtil.generateToken(saveUser.getUserId(), saveUser.getUsername());
    }
}
